package com.starmark.flow.sys.org.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starmark.common.base.service.AbstractUniqueBaseService;
import com.starmark.common.base.util.BeanMapper;
import com.starmark.common.typehandler.AES;
import com.starmark.flow.sys.org.entity.SysOrgUser;
import com.starmark.flow.sys.org.mapper.SysOrgUserMapper;
import com.starmark.flow.sys.org.service.ISysOrgUserService;
import com.starmark.flow.sys.org.vo.SysOrgUserVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * SysUser服务实现类
 *
 * @author starmark
 * @version 2016-08-27 22:39:42
 */
@Service("sysOrgUserService")
public class SysOrgUserServiceImpl extends AbstractUniqueBaseService<SysOrgUserMapper, SysOrgUser> implements ISysOrgUserService
          {

    @Override
    public SysOrgUser findUserByLoginName(String loginName) {
        return this.getBaseMapper().findUserByLoginName(loginName);
    }


    @Override
    public void buildPageSearch(Map<String, Object> params, QueryWrapper<SysOrgUser> eWrapper) {
        if (params.get("keyword") != null && StrUtil.isNotEmpty(params.get("keyword") + "")) {
            eWrapper.like("name", params.get("keyword") + "");
        }

    }




    @Override
    public boolean checkUserPassword(String userId, String password) {

        return this.getBaseMapper().checkUserPassword(userId, AES.encrypt(password));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveUserInfo(SysOrgUserVo sysOrgUserVo) {
        SysOrgUser sysOrgUser = BeanMapper.map(sysOrgUserVo, SysOrgUser.class);
        this.save(sysOrgUser);

        return sysOrgUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateUserInfo(SysOrgUserVo sysOrgUserVo) {
        SysOrgUser sysOrgUser = BeanMapper.map(sysOrgUserVo, SysOrgUser.class);
        //不更新密码
        sysOrgUser.setPassword(null);
        this.updateById(sysOrgUser);

        return sysOrgUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(String userId, String password) {
        Assert.hasText(userId, "用户ID不允许为空");
        SysOrgUser user = this.getById(userId);
        Assert.notNull(user, "用户不存在:" + userId);
        this.getBaseMapper().updatePwd(userId, AES.encrypt(password));
    }


    @Override
    public String getDbFieldCode() {
        return "login_name";
    }
}
